package com.hemaapp.yjnh.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.uu.utils.uuUtils;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.Order;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.bean.Order.BillChild;
import com.hemaapp.yjnh.utils.ImageUtils;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;

/**朋友代付订单详情，申请方和被申请方
 * @author GuiyouZhang
 * @author GuiyouZhang
 * Date：2015年10月20日 上午10:24:14
 * Email:guiyouzhang@163.com
 */
public class FriendPayDetailActivity extends BaseActivity implements OnClickListener {

	private TextView titleText;
	private ImageButton titleLeft;
	private Button titleRight;

	private TextView tvState;
	private TextView tvHint;
	private TextView tvContact;
	private TextView tvDate;
	private LinearLayout llGoods;
	private TextView tv_freight;
	private TextView tv_money;
	private TextView tvOrderNum;
	private TextView tvOrderTime;
	private TextView tvOrderStatus;
	private LinearLayout llExpress;
	private TextView tvExpressName;
	private TextView tvExpressNum;
	private LinearLayout llBottom;
	private TextView tvRefuse;
	private TextView tvPay;

	private Order order;//当前的订单
	private String order_id;//订单号
	private User user;
	private HemaButtonDialog hbDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_friendpay_order_detail);
		user = getApplicationContext().getUser();
		super.onCreate(savedInstanceState);
		EventBus.getDefault().register(this);
		init();
	}

	@Override
	protected void getExras() {
		order = (Order) mIntent.getSerializableExtra("order");
		if (order != null) {
			order_id = order.getId();
		}else {
			order_id = mIntent.getStringExtra("order_id");
			orderGet();
		}
	}

	@Override
	protected void findView() {
		titleText = (TextView) findViewById(R.id.title_text);
		titleLeft = (ImageButton) findViewById(R.id.title_left_btn);
		titleRight = (Button) findViewById(R.id.title_right_btn);

		tvState = (TextView)findViewById( R.id.tv_state );
		tvHint = (TextView)findViewById( R.id.tv_hint );
		tvContact = (TextView)findViewById( R.id.tv_contact );
		tvDate = (TextView)findViewById( R.id.tv_date );
//		tvMoney = (TextView)findViewById( R.id.tv_money );
		llGoods = (LinearLayout)findViewById( R.id.ll_goods );
		tv_freight = (TextView) findViewById(R.id.tv_freight);
		tv_money = (TextView) findViewById(R.id.tv_money);
		llExpress = (LinearLayout)findViewById( R.id.ll_express );
		tvExpressName = (TextView)findViewById( R.id.tv_express_name );
		tvExpressNum = (TextView)findViewById( R.id.tv_express_num );
		tvOrderNum = (TextView)findViewById( R.id.tv_order_num );
		tvOrderTime = (TextView)findViewById( R.id.tv_order_time );
		tvOrderStatus = (TextView)findViewById( R.id.tv_order_status );
		llBottom = (LinearLayout)findViewById( R.id.ll_bottom );
		tvRefuse = (TextView)findViewById( R.id.tv_refuse );
		tvPay = (TextView)findViewById( R.id.tv_pay );
	}

	@Override
	protected void setListener() {
		titleLeft.setOnClickListener(this);
		titleText.setText("订单详情");
		titleRight.setVisibility(View.GONE);

		if (order != null) {
			initBottomButton();
			setBottomButton();
		}
		tvPay.setOnClickListener(clickListener);
		tvRefuse.setOnClickListener(clickListener);
	}

	@Override
	public void onDestroy() {
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}
	
	private void init() {
		if (order != null) {
			try {
				setData();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void orderGet() {
		getNetWorker().orderGet(getApplicationContext().getUser().getToken(),
				order_id);
	}

	private void setData() throws Exception {
//		SpannableString divSpan = new SpannableString("¥"+ order.getTotal_fee()+"元(可用"+ order.getScore_fee()+"粮票)");
//		divSpan.setSpan(new ForegroundColorSpan (Color.parseColor("#ff3e3e")), 0, divSpan.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
		
		tvState.setText(getTradeStatus());
		tvHint.setText("申请代付:  ");
		tvHint.append(Html.fromHtml("<font color=#ff3e3e>¥"+order.getTotal_fee()+"元(可用</font>"));
        BaseUtil.addStampSign(mContext, tvHint, R.mipmap.food_stamp_red);
        tvHint.append(Html.fromHtml("<font color=#ff3e3e>"+order.getScore_fee()+ "粮票)</font>"));
//		tvHint.append(divSpan);
		String pay_client_id = order.getPay_client_id();//代付人id
		if (pay_client_id.equals(user.getId())) {
			tvContact.setText("申请人:  "+ order.getConsignee()+"  "+ order.getPhone());
		}else {
			tvContact.setText("代付人:  "+ order.getPay_client_nickname()+"  "+ order.getPay_client_username());
		}
		tvDate.setText(order.getRegdate());
		
		//动态添加多个商品
		if (llGoods.getChildCount() != 0) {
			llGoods.removeAllViews();
		}
		for (int i = 0; i < order.getChildren().size(); i++) {
			BillChild child = order.getChildren().get(i);
			View view = LayoutInflater.from(mContext).inflate(
					R.layout.item_order_goods, null);
			ItemViewHolder ivHolder = new ItemViewHolder();
			itemFindView(view, ivHolder);
			setItem(i, child, view, ivHolder);
			view.setTag(order.getChildren().get(i));
			view.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					BillChild child = (BillChild) v.getTag();
					Intent intent = BaseUtil.createBlogIntent(mContext, child.getType());
					intent.putExtra("blog_id", child.getBlog_id());
					mContext.startActivity(intent);
				}
			});
		}
		tv_freight.setText(order.getShipping_fee()+"元");
		tv_money.setText("¥"+ order.getTotal_fee()+"元");
		tvOrderNum.setText(order.getBill_sn());
		tvOrderTime.setText(order.getRegdate());
		tvOrderStatus.setText(getTradeStatus());
		String shipping_num = order.getShipping_num();
		if (shipping_num!=null && !shipping_num.isEmpty()) {
			llExpress.setVisibility(View.VISIBLE);
			tvExpressName.setText(order.getShipping_name());
			tvExpressNum.setText(shipping_num);
		}else {
			llExpress.setVisibility(View.GONE);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_left_btn:
			finish();
			break;
		}
	}

	private class ItemViewHolder {
		private ImageView img;
		private TextView name;
		private TextView price;
		private TextView amount;
		TextView tvCommit;
		TextView tvAfterSale;
		View div;
	}

	/**一个订单中的多个商品
	 * @param view
	 * @param ivHolder
	 */
	private void itemFindView(View view, ItemViewHolder ivHolder) {
		ivHolder.img = (ImageView) view.findViewById(R.id.img);
		ivHolder.name = (TextView) view.findViewById(R.id.good_name);
		ivHolder.price = (TextView) view.findViewById(R.id.price);
		ivHolder.amount = (TextView) view.findViewById(R.id.count);
		ivHolder.tvCommit = (TextView) view.findViewById(R.id.tv_commit);
		ivHolder.tvAfterSale = (TextView) view.findViewById(R.id.tv_aftersale);
		ivHolder.div = view.findViewById(R.id.divider);
	}
	
	private void setItem(int i, final BillChild child, View view, ItemViewHolder ivHolder) {
		ImageUtils.loadSmalImage(mContext, child.getImgurl(), ivHolder.img);
		ivHolder.name.setText(child.getName());
		ivHolder.price.setText("¥"+child.getPrice());
		ivHolder.amount.setText("x" + child.getBuycount());
		
		if (i == order.getChildren().size()-1) {
			ivHolder.div.setVisibility(View.GONE);
		}else {
			ivHolder.div.setVisibility(View.VISIBLE);
		}
		llGoods.addView(view);
	}

	@Override
	protected void callBeforeDataBack(HemaNetTask netTask) {
		BaseHttpInformation info = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (info) {
		case ORDER_SAVEOPERATE:
		case ORDER_GET:
			showProgressDialog("请稍候");
			break;
		default:
			break;
		}
	}

	@Override
	protected void callAfterDataBack(HemaNetTask netTask) {
		BaseHttpInformation info = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (info) {
		case ORDER_SAVEOPERATE:
		case ORDER_GET:
			cancelProgressDialog();
			break;
		default:
			break;
		}
	}

	@Override
	protected void callBackForServerSuccess(HemaNetTask netTask,
			HemaBaseResult baseResult) {
		BaseHttpInformation info = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (info) {
		case ORDER_SAVEOPERATE:
			String keytype = netTask.getParams().get("keytype");
			if ("1".equals(keytype) || "4".equals(keytype)) {
				showTextDialog("删除成功！");
			}else if ("2".equals(keytype)) {
				showTextDialog("确定收货成功！");
			}else if ("5".equals(keytype)) {
				showTextDialog("派送成功！");
			}else if ("3".equals(keytype) || "6".equals(keytype)) {
				showTextDialog("操作成功！");
			}else if ("14".equals(keytype)) {
				orderGet();
			}else if ("15".equals(keytype)) {
				showTextDialog("拒绝成功");
			}
//			Intent it = getIntent();
//			if ("1".equals(keytype)) {
//				it.putExtra("type", "1");
//			} else {
//				it.putExtra("type", "2");
//			}
//			it.putExtra("order", order);
//			setResult(RESULT_OK, it);
			setResult(RESULT_OK);
			EventBusMsg msg = new EventBusMsg();
			msg.setType(EventBusConfig.UPDATE_ORDER);
			EventBus.getDefault().post(msg);
			new Handler().postDelayed(new Runnable() {

				@Override
				public void run() {
					finish();
				}
			}, 500);
			break;
		case ORDER_GET:
			HemaArrayResult<Order> bResult = (HemaArrayResult<Order>) baseResult;
			order = bResult.getObjects().get(0);
			init();
			initBottomButton();
			setBottomButton();
			break;
		default:
			break;
		}
	}

	@Override
	protected void callBackForServerFailed(HemaNetTask netTask,
			HemaBaseResult baseResult) {
		BaseHttpInformation info = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (info) {
		case ORDER_SAVEOPERATE:
		case ORDER_GET:
			showTextDialog("操作失败");
			break;
		default:
			break;
		}
	}

	@Override
	protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
		BaseHttpInformation info = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (info) {
		case ORDER_SAVEOPERATE:
			showTextDialog("操作失败");
			break;
		case ORDER_GET:
			showTextDialog("获取订单详情失败");
			break;
		default:
			break;
		}
	}

	/**获取订单的状态
	 * @return
	 */
	private String getTradeStatus() {
		String status = "";
		//		订单状态	1：有效 2：已删除
		int statetype = Integer.parseInt(order.getStatetype());
		if (statetype == 2) {
			status = "代付已关闭";
			return status;
		}
		//代付状态	0非代付 1待确认 2接受代付 3拒绝代付
		int other_payflag = Integer.parseInt(order.getOther_payflag());
		switch (other_payflag) {
		case 1:
			status = "申请代付";
			break;
		case 2:
			status = "代付成功";
			break;
		case 3:
			status = "代付已拒绝";
			break;
		default:
			break;
		}
		return status;
	}
	
	/**初始化底部按钮，将全部按钮不显示
	 */
	private void initBottomButton() {
		llBottom.setVisibility(View.GONE);
		tvRefuse.setVisibility(View.GONE);
		tvPay.setVisibility(View.GONE);
	}
	
	/**根据不同的交易状态显示不同的处理按钮
     */
	private void setBottomButton() {
		//		订单状态	1：有效 2：已删除
		int statetype = Integer.parseInt(order.getStatetype());
		if (statetype == 2) {
			return;
		}
		//代付状态	0非代付 1待确认 2接受代付 3拒绝代付
		int other_payflag = Integer.parseInt(order.getOther_payflag());
		switch (other_payflag) {
		case 1://1待确认
			if (!order.getClient_id().equals(user.getId())) {//订单客户id和我的id不相同，说明是别人找我代付
				llBottom.setVisibility(View.VISIBLE);
				tvRefuse.setVisibility(View.VISIBLE);
				tvPay.setVisibility(View.VISIBLE);
			}
			break;
		default:
			break;
		}
	}
	private OnClickListener clickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.tv_refuse:
				hbDialog = new HemaButtonDialog(mContext);
		        hbDialog.setText("确定拒绝为对方代付吗？");
		        hbDialog.setLeftButtonText("取消");
		        hbDialog.setRightButtonText("确定");
		        hbDialog.setButtonListener(new HemaButtonDialog.OnButtonListener() {

		            @Override
		            public void onRightButtonClick(HemaButtonDialog dialog) {
		                dialog.cancel();
		                if (user != null && order !=null) {
		        			getNetWorker().orderSaveoperate(user.getToken(), order.getId(), "15", "无",
		        					"无", "无", "无");
		        		}
		            }

		            @Override
		            public void onLeftButtonClick(HemaButtonDialog dialog) {
		                dialog.cancel();
		            }
		        });
				break;
			case R.id.tv_pay:
				Intent itPay = new Intent(mContext, PayActivity.class);
			    itPay.putExtra("order", order);
				startActivity(itPay);
				break;
			default:
				break;
			}
		}
	};

	@Subscribe
	public void onEventMainThread(EventBusMsg msg) {
		if (msg.getType() == EventBusConfig.UPDATE_ORDER) {
			finish();
		}
	}
}
